const mongoose = require('mongoose');
const COLLECTIONS = require('./collections');

// 店铺营业时间模式
const BusinessHoursSchema = new mongoose.Schema({
  day: {
    type: String,
    required: true,
    enum: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
  },
  isOpen: {
    type: Boolean,
    default: true
  },
  openTime: {
    type: String,
    default: '09:00'
  },
  closeTime: {
    type: String,
    default: '22:00'
  }
});

// 店铺联系方式模式
const ContactInfoSchema = new mongoose.Schema({
  phone: String,
  email: String,
  wechat: String,
  qq: String,
  address: {
    province: String,
    city: String,
    district: String,
    detail: String
  }
});

// 店铺统计信息模式
const ShopStatsSchema = new mongoose.Schema({
  totalProducts: {
    type: Number,
    default: 0
  },
  totalSales: {
    type: Number,
    default: 0
  },
  totalOrders: {
    type: Number,
    default: 0
  },
  monthlyRevenue: {
    type: Number,
    default: 0
  },
  followers: {
    type: Number,
    default: 0
  }
});

// 店铺模式
const ShopSchema = new mongoose.Schema({
  // 基本信息
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 100
  },
  description: {
    type: String,
    required: true,
    maxlength: 500
  },
  logo: {
    type: String,
    default: 'https://via.placeholder.com/200x200/f0f0f0/999999?text=店铺'
  },
  banner: {
    type: String,
    default: 'https://via.placeholder.com/800x300/f0f0f0/999999?text=店铺横幅'
  },

  // 店主信息
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },

  // 店铺状态
  status: {
    type: String,
    enum: ['active', 'inactive', 'suspended', 'pending'],
    default: 'pending'
  },

  // 店铺类型
  type: {
    type: String,
    enum: ['official', 'flagship', 'authorized', 'personal'],
    default: 'personal'
  },

  // 主营类目 - 修改为字符串以避免文本索引问题
  categories: [{
    type: String
  }],

  // 主营类目字符串（用于文本搜索）
  categoriesText: {
    type: String,
    default: ''
  },

  // 店铺评分
  rating: {
    overall: {
      type: Number,
      default: 5.0,
      min: 0,
      max: 5
    },
    service: {
      type: Number,
      default: 5.0,
      min: 0,
      max: 5
    },
    logistics: {
      type: Number,
      default: 5.0,
      min: 0,
      max: 5
    },
    description: {
      type: Number,
      default: 5.0,
      min: 0,
      max: 5
    }
  },

  // 评价数量
  reviewCount: {
    type: Number,
    default: 0
  },

  // 联系方式
  contact: ContactInfoSchema,

  // 营业时间
  businessHours: [BusinessHoursSchema],

  // 店铺公告
  announcement: {
    type: String,
    maxlength: 200
  },

  // 店铺标签
  tags: [String],

  // 认证信息
  certification: {
    isVerified: {
      type: Boolean,
      default: false
    },
    verifiedAt: Date,
    businessLicense: String,
    certificationDocs: [String]
  },

  // 配送信息
  shipping: {
    freeShippingThreshold: {
      type: Number,
      default: 0
    },
    shippingFee: {
      type: Number,
      default: 0
    },
    supportedRegions: [String],
    averageDeliveryTime: {
      type: Number,
      default: 3 // 天数
    }
  },

  // 售后服务
  afterSales: {
    returnPolicy: {
      type: String,
      default: '7天无理由退货'
    },
    warrantyPeriod: {
      type: Number,
      default: 365 // 天数
    },
    supportRefund: {
      type: Boolean,
      default: true
    },
    supportExchange: {
      type: Boolean,
      default: true
    }
  },

  // 统计信息
  stats: ShopStatsSchema,

  // 关注用户
  followers: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }],

  // 店铺设置
  settings: {
    autoReply: {
      enabled: {
        type: Boolean,
        default: false
      },
      message: String
    },
    showContact: {
      type: Boolean,
      default: true
    },
    allowReviews: {
      type: Boolean,
      default: true
    }
  }
}, {
  timestamps: true
});

// 创建索引 - 修复文本索引问题
ShopSchema.index({ name: 'text', description: 'text', categoriesText: 'text' });
ShopSchema.index({ owner: 1 });
ShopSchema.index({ status: 1 });
ShopSchema.index({ 'rating.overall': -1 });
ShopSchema.index({ createdAt: -1 });

// 中间件：保存前更新categoriesText
ShopSchema.pre('save', function (next) {
  if (this.categories && this.categories.length > 0) {
    this.categoriesText = this.categories.join(' ');
  }
  next();
});

// 虚拟字段：店铺商品数量
ShopSchema.virtual('productCount', {
  ref: 'Product',
  localField: '_id',
  foreignField: 'shop',
  count: true
});

// 中间件：更新统计信息
ShopSchema.methods.updateStats = async function () {
  const Product = mongoose.model('Product');
  const Order = mongoose.model('Order');

  // 统计商品数量
  const productCount = await Product.countDocuments({ shop: this._id });

  // 统计订单相关数据（这里需要根据实际订单模型调整）
  // const orderStats = await Order.aggregate([...]);

  this.stats.totalProducts = productCount;
  await this.save();
};

const Shop = mongoose.model('Shop', ShopSchema, COLLECTIONS.SHOPS || 'shops');

module.exports = Shop;
